package com.seari.utils;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Executors;

public class GuavaLocalCacheUtils {

    private Logger logger = LoggerFactory.getLogger(getClass());

    // 缓存最大容量
    //private static int maxSize = 1;
    // 数据刷新线程池
    private static ListeningExecutorService refreshPool = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(20));

    public static LoadingCache<String, Object> cache = CacheBuilder.newBuilder()
            //.maximumSize(maxSize)//最多存放100个数据
           // .expireAfterWrite(10, TimeUnit.SECONDS)//缓存10秒，10秒之后进行回收
            .recordStats()//开启，记录状态数据功能
            .build(new CacheLoader<String, Object>() {
                //数据加载，默认返回-1，也可以是查询操作，如从DB查询
                @Override
                public Integer load(String key) throws Exception {
                    return -1;
                }});


    public static void main(String[] args) {

        GuavaLocalCacheUtils guavaLocalCacheUtils = new GuavaLocalCacheUtils();

        //只查询缓存，没有命中，即返回null
        System.out.println(guavaLocalCacheUtils.cache.getIfPresent("key1"));
        //put数据，放在缓存中
        guavaLocalCacheUtils.cache.put("key1", 1);
        System.out.println(guavaLocalCacheUtils.cache.getIfPresent("key1"));

        GuavaLocalCacheUtils guavaLocalCacheUtils2 = new GuavaLocalCacheUtils();
        GuavaLocalCacheUtils guavaLocalCacheUtils3 = new GuavaLocalCacheUtils();
        GuavaLocalCacheUtils guavaLocalCacheUtils4 = new GuavaLocalCacheUtils();
        GuavaLocalCacheUtils guavaLocalCacheUtils5 = new GuavaLocalCacheUtils();

        System.out.println(guavaLocalCacheUtils2.cache.getIfPresent("key1"));
        System.out.println(guavaLocalCacheUtils3.cache.getIfPresent("key1"));
    }
}